<?php
/**
 * Created by PhpStorm.
 * User: 王
 * Date: 2016/10/31
 * Time: 17:37
 */

namespace app\components\behaviors;

use  yii;
use yii\base\Behavior;
use yii\base\ErrorException;
use yii\db\ActiveRecord;
use app\models\Recover;

 class RecoverBehavior extends Behavior
{
    public function events()
    {
        return
            [
                ActiveRecord::EVENT_BEFORE_DELETE => 'deleteBefor',
            ];
    }
    public function saveRecover($gtable, $class_name, $deleted_by, $delete_time, $fid, $route = '')
    {
        $recover = new Recover;
        $recover->gtable = $gtable;
        $recover->class_name = $class_name;
        $recover->deleted_by = $deleted_by;
        $recover->delete_time = $delete_time;
        $recover->route = $route;
        $recover->fid = $fid;
        $recover->save();

    }
    public function deleteBefor($event)
    {
        $model = $this->owner;
        $delete_time = date("Y-m-d H:i:s");
        $deleted_by = Yii::$app->user->id;
        $className = get_class($model);
        $gtable = $model::tableName();
        $this->saveRecover($gtable, $className, $deleted_by, $delete_time, $model->primaryKey);
        /**@var $event \yii\base\ModelEvent */
        return $event->isValid = false;
    }

 }